package com.taotao.portal.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.common.utils.CookieUtils;
import com.taotao.pojo.TbUser;
import com.taotao.portal.service.impl.UserServiceImpl;

public class LoginInterceptor implements HandlerInterceptor {
	
	@Autowired
	private UserServiceImpl userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//Handler执行之前处理
		//判断用户是否登陆
		//1从cookie中取token
		String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
		//根据token换取用户信息，调用sso系统的接口
		TbUser user = userService.geTbUserByToken(token);
		//取不到用户信息
		if(null == user){
			//跳转到登陆页面，吧用户请求的url作为参数传递给登录页面。
			response.sendRedirect(userService.SSO_BASE_URL+userService.SSO_PAGE_LOGIN
					+ "?redirect=" + request.getRequestURL());
			System.out.println(request.getRequestURL());
			//返回false
			return false;
		}
		//返回值决定handler是否执行。true:执行,false:不执行
		//把用户信息放到request中,只需要在controller中判断request中是否包含user信息。
        request.setAttribute("user", user);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		 //handler执行之后，返回modelAndView之前

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		 //完成处理，返回modelAndView之后(已经响应了)
        //可以再次处理异常
	}

}
